import { Injectable } from '@angular/core';
import { Subject, Subscription } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class BroadcastService<B> {

  private subjectMap = new Map<B, Subject<any>>();

  constructor() { }

  get(name: B): Subject<any> {
    let subject = this.subjectMap.get(name);
    if (!subject) {
      subject = new Subject();
      this.subjectMap.set(name, subject);
    }

    return subject;
  }

  emit(name: B, data?: any) {
    const subject = this.get(name);
    subject.next(data);
  }

  subscribe(name: B, callback: (value: any) => void): Subscription {
    const subject = this.get(name);
    return subject.subscribe(callback);
  }
}
